package com.cj.park_dispatch.http;


import com.cj.park_dispatch.MyApplication;
import com.cj.park_dispatch.http.cookie.CookieManger;
import com.cj.smart_bike.http.HttpService;
import com.google.gson.Gson;

import java.io.File;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * 封装的请求工具类
 *
 * @author zengyi
 * create at 2017/1/10 9:40
 */
public class RestClient {
	public static final String TAG = "RestClient";
	private static Retrofit retrofit;
	private static HttpService sHttpService;
	private static OkHttpClient okHttpClient;
	private static final int DEFAULT_TIMEOUT = 60;
	private static final int HTTP_RESPONSE_DISK_CACHE_MAX_SIZE = 500 * 1024 * 1024;

	public HttpService getHttpService() {
		if (sHttpService == null) {
			sHttpService = getRetrofit().create(HttpService.class);
		}
		return sHttpService;
	}


	private Retrofit getRetrofit() {
		if (retrofit == null) {
			retrofit = new Retrofit.Builder()
					//.addConverterFactory(GsonConverterFactory.create())//加入json解析
					.addConverterFactory(CustomGsonConverterFactory.create(new Gson()))//加入json解析
					.addConverterFactory(ScalarsConverterFactory.create())//来增加字符串请求
					.addCallAdapterFactory(RxJava2CallAdapterFactory.create()) // 使用RxJava作为回调适配器
					.client(getClient())
					.baseUrl("")
					.build();
		}
		return retrofit;
	}


	private OkHttpClient getClient() {
		if (okHttpClient == null) {
			okHttpClient = new OkHttpClient.Builder()
					.addInterceptor(new LoggerInterceptor(TAG, true))//打印日志
					/*.addInterceptor(new LoggingInterceptor.Builder()
							.setLevel(Level.BASIC)
							.build())*/
					.cookieJar(new CookieManger())
					.addNetworkInterceptor(new CacheInterceptor())//设置缓存 这种方式只有get请求有效
					.addInterceptor(new CacheInterceptor())
					.cache(cache()) //设置缓存目录
					.addInterceptor(headerInterceptor) //设置头部信息
					//.addInterceptor(addQueryParameterInterceptor) //公共参数
					.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS) //超时
					.retryOnConnectionFailure(true) //失败重连
					.readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
					.writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
					.build();
		}
		return okHttpClient;
	}

	/**
	 * okhttp缓存目录设置
	 */
	private Cache cache() {
		//设置缓存路径
		File baseDir = MyApplication.instance
				.getCacheDir()
				.getAbsoluteFile();//程序安装目录下的临时目录
		File cacheDir = new File(baseDir, "ResponseCache");

		//设置缓存 500M
		return new Cache(cacheDir, HTTP_RESPONSE_DISK_CACHE_MAX_SIZE);
	}


	/**
	 * 公共参数
	 */
	private static Interceptor addQueryParameterInterceptor = chain -> {
		Request originalRequest = chain.request();
		Request request;
		//String method = originalRequest.method();
		//Headers headers = originalRequest.headers();
		HttpUrl modifiedUrl = originalRequest.url().newBuilder()
				// Provide your custom parameter here
				//.addQueryParameter("userName", UserCache.getInstance().getUserName())
				//.addQueryParameter("token", UserCache.getInstance().getToken())
				.build();
		request = originalRequest.newBuilder().url(modifiedUrl).build();

		return chain.proceed(request);
	};


	/**
	 * 头部信息
	 */
	private static Interceptor headerInterceptor = chain -> {

		Request originalRequest = chain.request();
		Request.Builder requestBuilder = originalRequest.newBuilder()
				.header("AppType", "TPOS")
				.header("Content-Type", "application/json")
				.header("Accept", "application/json")
				.method(originalRequest.method(), originalRequest.body());
		Request request = requestBuilder.build();
		return chain.proceed(request);
	};


}